/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pkg.util;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 *
 * @author will
 */
public class ImageUtil {

    public static byte[] resizeImageStream(InputStream is, int maxWidth, int maxHeight) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[8192];
        int n = is.read(buf);
        while (n >= 0) {
            baos.write(buf, 0, n);
            n = is.read(buf);
        }
        baos.close();

        return resizeImage(baos.toByteArray(), maxWidth, maxHeight);
    }

    public static byte[] resizeImage(byte[] rawImage, int maxWidth, int maxHeight) {
        ImagesService imagesService = ImagesServiceFactory.getImagesService();

        Image oldImage = ImagesServiceFactory.makeImage(rawImage);
        if (oldImage == null) {
            return null;
        }

        double xFactor = oldImage.getWidth() / 100.0;
        double yFactor = oldImage.getHeight() / 150.0;
        double factor = Math.max(xFactor, yFactor);
        Transform resize = ImagesServiceFactory.makeResize((int) (oldImage.getWidth() / factor), (int) (oldImage.getHeight() / factor));

        Image newImage = imagesService.applyTransform(resize, oldImage);

        return newImage.getImageData();
    }

    public static String getContentType(Image image) {
        Image.Format f = image.getFormat();

        if (f.equals(Image.Format.BMP)) {
            return "image/bmp";
        } else if (f.equals(Image.Format.GIF)) {
            return "image/gif";
        } else if (f.equals(Image.Format.ICO)) {
            return "image/ico";
        } else if (f.equals(Image.Format.JPEG)) {
            return "image/jpeg";
        } else if (f.equals(Image.Format.PNG)) {
            return "image/png";
        } else if (f.equals(Image.Format.TIFF)) {
            return "image/tiff";
        }

        return null;
    }
}
